// import { OPFetch } from '@ones-op/fetch'
import type { PluginRequest, PluginResponse } from '@ones-op/node-types'
import { fetchONES } from '@ones-op/node-fetch'

// 获取全部的工作项
export async function getIssueTypes(teamId: string) {
  const url = `/team/${teamId}/issue_type_configs`
  const response = await fetchONES({
    path: url,
    method: 'GET',
  })
  return (response?.body as any).issue_type_configs
}

export function genRandonStr() {
  // 返回随机的8位字符串，只能是小写字母，大写字母和数字
  let str = ''
  for (let i = 0; i < 8; i++) {
    const random = Math.floor(Math.random() * 3)
    if (random === 0) {
      str += String.fromCharCode(Math.floor(Math.random() * 26) + 65)
    } else if (random === 1) {
      str += String.fromCharCode(Math.floor(Math.random() * 26) + 97)
    } else {
      str += Math.floor(Math.random() * 10)
    }
  }
  return str
}

// 考题 1-5 实现往当前团队下新增"缺陷"工作项
export async function addTask(request: PluginRequest): Promise<PluginResponse> {
  const headers = request.headers
  const body = request.body as any
  const teamId = headers['Ones-Check-Id']
  const userId = headers['Ones-User-Id']
  const issueTypes = await getIssueTypes(teamId)
  // 获取【缺陷】的id
  const bugId = issueTypes.find((item) => item.name === '缺陷')?.issue_type_uuid
  const url = `/team/${teamId}/tasks/add2`
  const response = await fetchONES({
    path: url,
    method: 'POST',
    body: {
      tasks: [
        {
          uuid: userId + genRandonStr(),
          assign: userId,
          summary: body.summary,
          parent_uuid: '',
          project_uuid: body.project_uuid,
          issue_type_uuid: bugId,
          // "priority":"KL2WUbkx",
          desc: body.desc,
        },
      ],
    },
  })
  return {
    body: {
      data: response?.body,
    },
  }
}
